<template>
  <div ref="chartRef" class="chart"></div>
</template>

<script setup>
import { onMounted, onBeforeUnmount, ref, watch } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  option: { type: Object, required: true },
  timestamp: { type: Number, required: false, default: 0 }
});

const chartRef = ref(null);
let chartInstance = null;

const initChart = () => {
  if (!chartRef.value) return;
  chartInstance = echarts.init(chartRef.value);
  chartInstance.setOption(props.option);
};

const resizeChart = () => {
  chartInstance?.resize();
};

onMounted(() => {
  initChart();
  window.addEventListener('resize', resizeChart);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart);
  chartInstance?.dispose();
});

// watch(() => props.option, () => {
//   if (chartInstance) {
//     chartInstance.setOption(props.option);
//   }
// }, { deep: true });
watch(() => props.timestamp, () => {
  if (chartInstance) {
    chartInstance.clear();
    chartInstance.setOption(props.option);
  }
});
</script>

<style scoped>
.chart {
  width: 100%;
  height: 400px;
  min-width: 400px;
}
</style>